package org.hr.xtime.absence

import org.hr.organisation.OrganisationService;
import org.hr.xtime.AbsenceService;
import org.hr.xtime.user.Employee;

class AbsenceController {
	
	OrganisationService organisationService
	AbsenceService absenceService

	/**
	 * @param view - week, month, year, custom
	 * @param weekOfYear - by default is the number of the current week in the year (only for view=week)
	 * @param month - by default is the number of the current month in the year (only for view=month
	 * @param year - by default is the number of the current year
	 * @param employees - the comma separated list with userIds to show as a line
	 * @param 
	 * @return
	 */
    def index(ViewCommand cmd) {
		boolean valid = cmd.parseParams(params)
		if(!valid) redirect(action:"index", params:[view:cmd.view,employees:cmd.usersList,year:cmd.year,month:cmd.month+1,weekOfYear:cmd.weekOfYear])
		
    	Calendar cal = Calendar.getInstance();

		Date dateFrom
		Date dateTo
		if(cmd.view == "week"){
			cal.clear();
			cal.set(Calendar.WEEK_OF_YEAR, cmd.weekOfYear);
			cal.set(Calendar.YEAR, cmd.year);
			
			// Now get the first and last day of week.
			dateFrom = cal.getTime();
			dateTo = dateFrom.plus(6) 
		}
		if(cmd.view == "month"){
			cal.clear();
			cal.set(Calendar.MONTH, cmd.month);
			cal.set(Calendar.YEAR, cmd.year);
			
			// Now get the first and last day of the month.
			dateFrom = cal.getTime();
			dateTo = dateFrom + cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)-1
		}
		
		List<Date> calDays = (dateFrom..dateTo).toList()
		List<Employee> employees = cmd.employees
		
		List<Day> days 
		List rows = []
		List cells = []
		Day tmp
		
		employees.each{employee->
			cells = []
			days = Day.findAllByEmployeeAndDateBetween(employee,dateFrom,dateTo,[sort: "date", order: "asc"])
			calDays.each {calDay->
				tmp = days.find {d-> d.date == calDay}
				if(tmp==null){
					cells.add(calDay)
				}else{
					cells.add(tmp)
				}	
			}
			rows.add(cells)
		}
		
		Map results = [rows: rows, calDays: calDays, employees:employees]
		results.put("balance",balance(cmd,dateFrom,dateTo))
		
		render(view: "index", model: results)
	}
	
	Map balance(ViewCommand cmd, Date dateFrom, Date dateTo){
		Map results = [:]
		
		cmd.employees.each{employee->
			results.put((employee),absenceService.calculateBalance(employee, dateFrom, dateTo))
		}
		return results
	}
	
	def getMyCollegues(){
		StringBuffer usersList = new StringBuffer()
		organisationService.getSiblings(session.user.userId).each{
			usersList.append(it.userId).append(",")
		}
		println usersList
		render usersList.toString().substring(0, usersList.size()-2)
		
	}

}

class ViewCommand{

	OrganisationService organisationService = new OrganisationService();
		
	Calendar now
	String view
	Integer weekOfYear
	Integer month
	Integer year
	List<Employee> employees = []
	def usersList
	
	boolean parseParams(params){
		
		params?:[:]
		boolean result = true
		
		now = Calendar.getInstance()
		month = params?.int("month")?.minus(1)
		year = params?.int("year")
		usersList = params.employees
		
		//view param handling
		view = params.view
		if(view==null) view = "month"
		if(!(view in ["month","week","year"])) view = "month"
		
		// weekOfYear
		weekOfYear = params.int("weekOfYear")
		if(weekOfYear==null) weekOfYear = now.get(Calendar.WEEK_OF_YEAR)
		
		//month
		if(month==null) month = now.get(Calendar.MONTH)
		
		//year
		if(year==null){
			year = now.get(Calendar.YEAR)
			result = false
		} 
		
		//usersList
		if(usersList==null){
			String users = ""
			organisationService.getSiblings(session.user.userId).each{
				users = users.concat(it.userId).concat(",")
			}
			usersList=users.concat(organisationService.getBoss(session.user.userId).userId)
			result=false
		}
		employees =[]
		Employee e
		usersList.split(",").each {it->
			e = Employee.findByUserId(it)
			if(e!=null) employees.add(e)
		}
		
		return result
	}
}